namespace GemBox.Spreadsheet
{
    using System;

    internal class NameFormulaToken : FormulaToken
    {
        private ushort nameIndex;
        private ExcelWorksheet sheet;

        public NameFormulaToken(FormulaTokenCode code, ExcelWorksheet sheet) : base(code, 5, FormulaTokenType.Operand)
        {
            this.sheet = sheet;
        }

        public override byte[] ConvertToBytes()
        {
            byte[] array = base.ConvertToBytes();
            BitConverter.GetBytes(this.nameIndex).CopyTo(array, 1);
            return array;
        }

        public override void DelayInitialize(object[] data)
        {
            string str = data[0] as string;
            ExcelWorksheet worksheet = data[1] as ExcelWorksheet;
            this.nameIndex = (ushort) (Array.IndexOf<string>(worksheet.NamedRanges.Names, str) + 1);
        }

        public override void Read(byte[] rpnBytes, int startIndex)
        {
            this.nameIndex = BitConverter.ToUInt16(rpnBytes, startIndex + 1);
        }

        public override string ToString()
        {
            return this.sheet.NamedRanges.Names[this.nameIndex];
        }
    }
}
